// pages/main/home/home.js
const { authManager } = require('../../../utils/auth.js');

Page({
  data: {
    statusBarHeight: 0, // 状态栏高度
    customBarHeight: 0, // 自定义导航栏总高度
    userInfo: {},
    searchKeyword: '', // 搜索关键词
    currentTab: 'message', // 默认选中"我的消息"标签
    unreadMessageCount: 0, // 未读消息数量
    unreadProjectCount: 0, // 未读项目消息数量
    unreadTodoCount: 0, // 未读待办事项数量
    unreadWarningCount: 0, // 未读预警信息数量
    unreadDailyCount: 0, // 未读工作日报数量
    unreadReportCount: 0, // 未读最新动态数量
    unreadTimeCount: 0, // 未读工时记录数量
    totalMessageCount: 0, // 消息总数
    messageList: [],
    projectList: [],
    todoList: [],
    warningList: [],
    dailyList: [],
    isLoading: false,
    loadingMore: false,
    hasMore: true,
    // 侧边栏状态
    sidebarCollapsed: false, // 侧边栏是否收起，默认展开
    // 为每个标签维护独立的分页状态，避免跨标签状态串扰
    tabState: {
      message: { loadingMore: false, hasMore: true, loadTimes: 0 },
      project: { loadingMore: false, hasMore: true, loadTimes: 0 },
      todo: { loadingMore: false, hasMore: true, loadTimes: 0 },
      warning: { loadingMore: false, hasMore: true, loadTimes: 0 },
      daily: { loadingMore: false, hasMore: true, loadTimes: 0 },
      report: { loadingMore: false, hasMore: true, loadTimes: 0 },
      time: { loadingMore: false, hasMore: true, loadTimes: 0 }
    },
    reportList: [],
    timeList: [],
    array: ['', '', ],
    index: 0,
  },

bindPickerChange: function (e) {
  console.log(e)
    this.setData({
      index: e.detail.value
});
},

// 切换侧边栏状态
toggleSidebar() {
  this.setData({
    sidebarCollapsed: !this.data.sidebarCollapsed
  });
},

  // 搜索输入变化（Lin UI 的 linchange 事件）
  onSearchChange(e) {
    const keyword = e.detail.value || '';
    this.setData({ searchKeyword: keyword });
    // 实时搜索
    this.filterMessages(keyword);
  },

  // 搜索确认（Lin UI 的 linconfirm 事件）
  onSearchConfirm(e) {
    const keyword = e.detail.value || '';
    this.setData({ searchKeyword: keyword });
    this.filterMessages(keyword);
    console.log('搜索确认:', keyword);
  },

  // 清除搜索（Lin UI 的 linclear 事件）
  onSearchClear() {
    this.setData({ searchKeyword: '' });
    // 恢复原始数据
    this.loadCurrentTabData();
    console.log('清除搜索');
  },

  // 取消搜索（Lin UI 的 lincancel 事件）
  onSearchCancel() {
    this.setData({ searchKeyword: '' });
    // 恢复原始数据
    this.loadCurrentTabData();
    console.log('取消搜索');
  },

  // 筛选消息
  filterMessages(keyword) {
    if (!keyword) {
      this.loadCurrentTabData();
      return;
    }

    const lowerKeyword = keyword.toLowerCase();
    const currentTab = this.data.currentTab;
    const listKey = `${currentTab}List`;
    const originalList = this.data[listKey] || [];

    const filtered = originalList.filter(item => {
      const title = (item.title || '').toLowerCase();
      const sender = (item.sender || '').toLowerCase();
      const text = (item.text || '').toLowerCase();
      return title.includes(lowerKeyword) || 
             sender.includes(lowerKeyword) || 
             text.includes(lowerKeyword);
    });

    this.setData({
      [listKey]: filtered
    });
  },

  // 加载当前标签的数据
  loadCurrentTabData() {
    switch(this.data.currentTab) {
      case 'message':
        this.loadMessageData();
        break;
      case 'project':
        this.loadProjectData();
        break;
      case 'todo':
        this.loadTodoData();
        break;
      case 'warning':
        this.loadWarningData();
        break;
      case 'daily':
        this.loadDailyData();
        break;
    }
  },

  onLoad() {
    // 获取系统信息，适配状态栏高度
    const systemInfo = wx.getSystemInfoSync();
    const statusBarHeight = systemInfo.statusBarHeight || 0;
    console.log('状态栏高度',statusBarHeight) 
    // 自定义导航栏高度 = 状态栏高度 + 导航栏内容高度(44px)
    const customBarHeight = statusBarHeight + 44;
    
    this.setData({
      statusBarHeight: statusBarHeight,
      customBarHeight: customBarHeight
    });
    
    // 验证登录状态
    if (!authManager.pageLoginCheck()) {
      return;
    }
    
    this.loadUserInfo();
    // 加载默认标签的数据
    this.loadMessageData();
    // 获取所有标签的未读消息数量
    this.getUnreadCounts();
  },
  onShareAppMessage() {
  },
  onShow() {
    // 验证登录状态
    if (!authManager.pageLoginCheck()) {
      return;
    }
    
    this.loadUserInfo();
    // 如果需要每次显示页面都刷新数据，可以在这里调用相应的加载方法
    // 根据当前选中的标签加载数据
    switch(this.data.currentTab) {
      case 'message':
        this.loadMessageData();
        break;
      case 'project':
        this.loadProjectData();
        break;
      case 'todo':
        this.loadTodoData();
        break;
      case 'warning':
        this.loadWarningData();
        break;
      case 'daily':
        this.loadDailyData();
        break;
    }
    this.updateTotalMessageCount(); // 在onShow时更新总数
  },

  // 加载用户信息
  loadUserInfo() {
    try {
      const userInfo = wx.getStorageSync('user_info');
      console.log('用户'+userInfo.zh_name+'进入消息页面')
      if (userInfo) {
        this.setData({
          userInfo: userInfo
        });
      }
    } catch (e) {
      console.error('获取用户信息失败:', e);
    }
  },
  
  // 切换标签
  switchTab(e) {
    const tab = e.currentTarget.dataset.tab;
    if (this.data.currentTab !== tab) {
      // 同步全局提示状态为该 tab 的状态，避免跨标签残留
      const ts = this.data.tabState[tab] || { loadingMore: false, hasMore: true };
      this.setData({
        currentTab: tab,
        loadingMore: ts.loadingMore,
        hasMore: ts.hasMore
      });
      
      // 根据不同标签加载不同数据
      switch(tab) {
        case 'message':
          this.loadMessageData();
          break;
        case 'project':
          this.loadProjectData();
          break;
        case 'todo':
          this.loadTodoData();
          break;
        case 'warning':
          this.loadWarningData();
          break;
        case 'daily':
          this.loadDailyData();
          break;
        case 'report':
          this.loadReportData();
          break;
        case 'time':
          this.loadTimeData();
          break;
      }
    }
  },
  
  // 加载消息数据
  loadMessageData() {
    // 这里添加加载消息数据的逻辑
    console.log('加载消息数据');
    // 模拟获取未读消息数量
    this.getUnreadCounts('message');
  },
  
  // 加载项目数据
  loadProjectData() {
    // 这里添加加载项目数据的逻辑
    console.log('加载项目数据');
    // 模拟获取未读项目消息数量
    this.getUnreadCounts('project');
  },
  
  // 加载待办事项数据
  loadTodoData() {
    // 这里添加加载待办事项数据的逻辑
    console.log('加载待办事项数据');
    // 模拟获取未读待办事项数量
    this.getUnreadCounts('todo');
  },
  
  // 加载预警信息数据
  loadWarningData() {
    // 这里添加加载预警信息数据的逻辑
    console.log('加载预警信息数据');
    // 模拟获取未读预警信息数量
    this.getUnreadCounts('warning');
  },
  
  // 加载工作日报数据
  loadDailyData() {
    // 这里添加加载工作日报数据的逻辑
    console.log('加载工作日报数据');
    // 模拟获取未读工作日报数量
    this.getUnreadCounts('daily');
  },

  // 加载最新动态
  loadReportData() {
    console.log('加载最新动态数据');
    this.getUnreadCounts('report');
  },

  // 加载我的工时
  loadTimeData() {
    console.log('加载我的工时数据');
    this.getUnreadCounts('time');
  },
  


  // 获取未读消息数量
  getUnreadCounts(type) {
    const counts = { message: 15, project: 8, todo: 12, warning: 13, daily: 30, report: 13, time: 18 };
    const statuses = ['unread','read','urgent','important'];
    const senderMap = { message: '系统', project: '项目经理', todo: '系统', warning: '监控平台', daily: '日报提交人', report: '系统动态', time: '本人' };
    const titleMap = { message: '我的消息', project: '项目消息', todo: '待办事项', warning: '预警信息', daily: '工作日报', report: '最新动态', time: '工时记录' };
    const buildList = (kind, count) => {
      const list = [];
      for (let i = 1; i <= count; i++) {
        const status = statuses[(i - 1) % statuses.length];
        const day = String(20 + (i % 10)).padStart(2, '0');
        const hour = String(8 + (i % 10)).padStart(2, '0');
        list.push({
          id: i,
          title: `${titleMap[kind]}${i}`,
          time: `2025-11-${day} ${hour}:30`,
          sender: senderMap[kind],
          text: `${titleMap[kind]}内容${i}`,
          status
        });
      }
      return list;
    };
    const messageList = buildList('message', counts.message);
    const projectList = buildList('project', counts.project);
    const todoList = buildList('todo', counts.todo);
    const warningList = buildList('warning', counts.warning);
    const dailyList = buildList('daily', counts.daily);
    const reportList = buildList('report', counts.report);
    const timeList = buildList('time', counts.time);
    const calcUnread = (list) => (list || []).filter(x => x.status !== 'read').length;
    const unreadMessageCount = calcUnread(messageList);
    const unreadProjectCount = calcUnread(projectList);
    const unreadTodoCount = calcUnread(todoList);
    const unreadWarningCount = calcUnread(warningList);
    const unreadDailyCount = calcUnread(dailyList);
    const unreadReportCount = calcUnread(reportList);
    const unreadTimeCount = calcUnread(timeList);
    this.setData({
      messageList,
      projectList,
      todoList,
      warningList,
      dailyList,
      reportList,
      timeList,
      unreadMessageCount,
      unreadProjectCount,
      unreadTodoCount,
      unreadWarningCount,
      unreadDailyCount,
      unreadReportCount,
      unreadTimeCount,
      array:['选项1','选项2']
    });
    this.updateTotalMessageCount();
  },

  // 更新消息总数
  updateTotalMessageCount() {
    const { unreadMessageCount, unreadProjectCount, unreadTodoCount, unreadWarningCount, unreadDailyCount } = this.data;
    const total = unreadMessageCount + unreadProjectCount + unreadTodoCount + unreadWarningCount + unreadDailyCount;
    this.setData({
      totalMessageCount: total
    });
    if (total > 0) {
      wx.setTabBarBadge({
        index: 0,
        text: String(total)
      });
    } else {
      wx.removeTabBarBadge({
        index: 0
      });
    }
  },
  // scroll-view 下拉刷新回调
  onRefresherRefresh() {
    if (this.data.isLoading) return;
    this.setData({ isLoading: true });

    // 刷新时重置当前 tab 的分页状态
    const tab = this.data.currentTab;
    const ts = this.data.tabState;
    ts[tab] = { loadingMore: false, hasMore: true, loadTimes: 0 };
    this.setData({ tabState: ts, hasMore: true, loadingMore: false });

    // 根据当前 tab 重新加载该 tab 数据
    switch (tab) {
      case 'message':
        this.loadMessageData();
        break;
      case 'project':
        this.loadProjectData();
        break;
      case 'todo':
        this.loadTodoData();
        break;
      case 'warning':
        this.loadWarningData();
        break;
      case 'daily':
        this.loadDailyData();
        break;
    }

    // 模拟请求完成后结束刷新动画
    setTimeout(() => {
      this.setData({ isLoading: false });
    }, 1000);
  },

  // scroll-view 触底加载更多
  onReachBottom() {
    const tab = this.data.currentTab;
    const ts = this.data.tabState;
    const state = ts[tab] || { loadingMore: false, hasMore: true, loadTimes: 0 };

    if (state.loadingMore || !state.hasMore) return;

    // 更新当前 tab 的 loadingMore -> true，并同步到全局显示
    state.loadingMore = true;
    ts[tab] = state;
    this.setData({ tabState: ts, loadingMore: true });

    // 模拟分页加载：根据当前 tab 追加数据
    const append = (listKey, items) => {
      const list = this.data[listKey] || [];
      this.setData({ [listKey]: list.concat(items) });
    };

    setTimeout(() => {
      state.loadTimes = (state.loadTimes || 0) + 1;

      switch (tab) {
        case 'message':
          append('messageList', [
            { id: Date.now(), title: '更多消息', time: '刚刚', sender: '系统', text: '加载更多消息...' }
          ]);
          break;
        case 'project':
          append('projectList', [
            { id: Date.now(), title: '更多项目', time: '刚刚', sender: '项目经理', text: '加载更多项目...' }
          ]);
          break;
        case 'todo':
          append('todoList', [
            { id: Date.now(), title: '更多待办', time: '刚刚', sender: '系统', text: '加载更多待办...' }
          ]);
          break;
        case 'warning':
          append('warningList', [
            { id: Date.now(), title: '更多预警', time: '刚刚', sender: '系统', text: '加载更多预警...' }
          ]);
          break;
        case 'daily':
          append('dailyList', [
            { id: Date.now(), title: '更多日报', time: '刚刚', sender: '系统', text: '加载更多日报...' }
          ]);
          break;
      }

      // 示例：每个 tab 加载 3 次后到底
      if (state.loadTimes >= 3) {
        state.hasMore = false;
      }

      // 结束当前 tab 的 loading，回写并同步到全局显示
      state.loadingMore = false;
      ts[tab] = state;
      this.setData({ tabState: ts, loadingMore: state.loadingMore, hasMore: state.hasMore });
    }, 1000);
  },
  //点击消息处理函数
  tapPress(e){
    const index = e.currentTarget.dataset.index;
    const type = e.currentTarget.dataset.type;
    const listKey = `${type}List`;
    const list = this.data[listKey] || [];
    // 将当前列表与索引缓存，避免 query 过长
    wx.setStorageSync('home_detail_payload', { type, list, currentIndex: index });
    wx.navigateTo({
      url: `/pages/main/home-message-detail/home-message-detail?type=${type}`
    });
  },
  // 长按消息处理函数
  longPressMessage(e) {
    const index = e.currentTarget.dataset.index;
    const type = e.currentTarget.dataset.type;
    console.log('长按消息', index, type);
    // 设置长按状态，触发样式变化
    this.setData({
      [`${type}List[${index.id-1}].isPressed`]: true
    });
    
    // 显示操作菜单
    wx.showActionSheet({
      itemList: type === 'message' ? ['message标记为已读', '标记为未读', '切换置顶'] : type === 'project' ? ['project标记为已读', '标记为未读', '切换置顶'] : type === 'warning' ? ['warningt标记为已读', '标记为未读', '切换置顶'] : type === 'daily' ? ['daily标记为已读', '标记为未读', '切换置顶'] : ['todo 标记为已读', '标记为未读'],
      success: (res) => {
        if (res.tapIndex === 0) {
          // 标记为已读的逻辑
          console.log(type,'标记为已读', index);
        } else if (res.tapIndex === 1) {
          // 标记为未读的逻辑
          console.log(type,'标记为未读', index);
        } else if (res.tapIndex === 2) {
          // 切换置顶的逻辑
          console.log(type,'切换置顶', index); 
        }
      },
      complete: () => {
        // 操作完成后，取消长按状态
        setTimeout(() => {
          this.setData({
            [`${type}List[${index.id-1}].isPressed`]: false
          });
        }, 100);
      }
    });
  },
  
  // 触摸开始事件
  touchStart(e) {
    this.setData({
      touchStartX: e.changedTouches[0].clientX
    });
  },
  
  // 触摸结束事件
  touchEnd(e) {
    const touchEndX = e.changedTouches[0].clientX;
    const diff = touchEndX - this.data.touchStartX;
    
    // 设置滑动的最小距离，避免误触
    const minDistance = 50;
    
    if (Math.abs(diff) < minDistance) {
      return; // 滑动距离太小，不做处理
    }
    
    // 获取当前标签的索引
    const tabs = ['message', 'project', 'todo', 'warning', 'daily'];
    const currentIndex = tabs.indexOf(this.data.currentTab);
    
    if (diff > 0) {
      // 向右滑动，切换到上一个标签
      if (currentIndex > 0) {
        this.switchToTab(tabs[currentIndex - 1]);
      }
    } else {
      // 向左滑动，切换到下一个标签
      if (currentIndex < tabs.length - 1) {
        this.switchToTab(tabs[currentIndex + 1]);
      }
    }
  },
  
  // 切换到指定标签
  switchToTab(tab) {
    if (this.data.currentTab !== tab) {
      const ts = this.data.tabState[tab] || { loadingMore: false, hasMore: true };
      this.setData({
        currentTab: tab,
        loadingMore: ts.loadingMore,
        hasMore: ts.hasMore
      });
      
      // 根据不同标签加载不同数据
      switch(tab) {
        case 'message':
          this.loadMessageData();
          break;
        case 'project':
          this.loadProjectData();
          break;
        case 'todo':
          this.loadTodoData();
          break;
        case 'warning':
          this.loadWarningData();
          break;
        case 'daily':
          this.loadDailyData();
          break;
      }
    }
  }
});
